<template>
    <div id="cesiumContainer"></div>
    <teleport to="body">
        <div class="mps-tip" v-if="currentMps.id" id="mpsTip">
            <div class="tip-header">
                <h4>{{ currentMps.name }}</h4>
                <span class="tip-type" :class="currentMps.type">{{ getPoiTypeLabel(currentMps.type) }}</span>
                <span v-if="currentMps.isAlert" class="alert-badge">⚠️ 预警</span>
            </div>
            <div class="tip-content" v-if="currentMps.data">
                <div v-if="currentMps.type === 'scenic'" class="scenic-info">
                    <p><span class="label">当前游客:</span> {{ currentMps.data.currentVisitors }}/{{
                        currentMps.data.capacity }}</p>
                    <p><span class="label">环境温度:</span> {{ currentMps.data.temperature }}°C</p>
                    <p><span class="label">湿度:</span> {{ currentMps.data.humidity }}%</p>
                </div>
                <div v-else-if="currentMps.type === 'monitor'" class="monitor-info">
                    <p><span class="label">设备类型:</span> {{ currentMps.data.deviceType }}</p>
                    <p><span class="label">分辨率:</span> {{ currentMps.data.resolution }}</p>
                    <p><span class="label">覆盖范围:</span> {{ currentMps.data.coverage }}</p>
                </div>
                <div v-else-if="currentMps.type === 'workpoint'" class="workpoint-info">
                    <p><span class="label">工程ID:</span> {{ currentMps.data.id }}</p>
                    <p><span class="label">类型:</span> 工程标记点</p>
                </div>
                <div v-else-if="currentMps.type === 'service'" class="service-info">
                    <p><span class="label">服务类型:</span> {{ currentMps.data.serviceType || '公共服务' }}</p>
                    <p><span class="label">开放时间:</span> {{ currentMps.data.openTime || '全天' }}</p>
                </div>
                <div v-else-if="currentMps.type === 'dining'" class="dining-info">
                    <p><span class="label">餐饮类型:</span> {{ currentMps.data.cuisineType || '综合餐饮' }}</p>
                    <p><span class="label">营业时间:</span> {{ currentMps.data.businessHours || '8:00-22:00' }}</p>
                </div>
                <div v-else class="other-info">
                    <p><span class="label">状态:</span> {{ currentMps.data.status || '正常' }}</p>
                </div>
                <p v-if="currentMps.data.description" class="description">{{ currentMps.data.description }}</p>
            </div>
            <button class="close-btn" @click="currentMps = {}">×</button>
        </div>
    </teleport>

    <!-- 监控视频弹窗 - 使用Teleport渲染到body -->
    <Teleport to="body">
        <div v-if="showMonitorVideo" class="monitor-video-modal">
            <div class="video-modal-overlay" @click="closeMonitorVideo"></div>
            <div class="video-modal-content">
                <div class="video-header">
                    <h3>{{ selectedPoi?.name || '监控画面' }}</h3>
                    <button class="video-close-btn" @click="closeMonitorVideo">×</button>
                </div>
                <div class="video-container">
                    <video ref="videoPlayerRef" :src="currentVideoSource" controls autoplay muted class="monitor-video"
                        @loadstart="() => console.log('视频开始加载')" @error="(e) => console.error('视频加载错误:', e)">
                        您的浏览器不支持视频播放
                    </video>
                </div>
                <div class="video-info" v-if="selectedPoi">
                    <div class="info-item">
                        <span class="label">设备类型:</span>
                        <span class="value">{{ selectedPoi.data?.deviceType || '高清摄像头' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">分辨率:</span>
                        <span class="value">{{ selectedPoi.data?.resolution || '1080P' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">位置:</span>
                        <span class="value">{{ selectedPoi.data?.address || selectedPoi.name }}</span>
                    </div>
                </div>
            </div>
        </div>
    </Teleport>
</template>

<script setup>
import {
    computed,
    inject,
    onMounted,
    getCurrentInstance,
    ref,
    reactive,
    onBeforeUnmount,
    nextTick,
    watch,
} from "vue";
if (import.meta.env.NODE_ENV === "development") {
  window.CESIUM_BASE_URL =
    import.meta.env.BASE_URL + "node_modules/cesium/Build/Cesium/";
}
import * as Cesium from "cesium";
import img1 from "../../assets/images/test.png";
// import { amapPoiData } from './amapPoiData.js';
import { getMonitorVideoSource } from './amapPoiTypes.js';

import useDataStore from '@/stores/data.js';
import { storeToRefs } from 'pinia';
const store = useDataStore();
const { amapPoiData, listTypes, patrolPlans } = storeToRefs(store)
delete Cesium.Ion.defaultAccessToken;
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2NzZkMWM0Zi1mNDliLTQzZjItOGE1Mi05OWMzZDQzNjZmMGMiLCJpZCI6MTg0NjUwLCJpYXQiOjE3MDI2MzI0NjB9.DIfMjN1CxORwbOy9_9Oal_1LjbBU-Cgeb0u6Ty_gGC0";
// Props 接收筛选参数
const props = defineProps({
    activeFilter: {
        type: String,
        default: 'all'
    }
});


// Emits
const emit = defineEmits(['poi-selected', 'stats-updated']);

const { proxy } = getCurrentInstance();
const currentMps = ref({});

// 视频相关状态
const showMonitorVideo = ref(false);
const currentVideoSource = ref('');
const videoPlayerRef = ref(null);

let viewer;

// POI相关
const poiEntities = ref([]);
const selectedPoi = ref(null);

// 计算可见POI
const visiblePois = computed(() => {
    if (props.activeFilter === 'all') {
        return amapPoiData.value;
    }
    return amapPoiData.value.filter(poi => poi.type == props.activeFilter);
});

// 在文件顶部添加资源加载优化
Cesium.Resource.fetchOptions = {
    retryAttempts: 1,
    retryCallback: undefined,
    throttle: true,
    throttleLimit: 6,
    preferBlob: true,
};

// 在setup作用域顶部声明需要清理的引用
const handlers = [];
let infoBox = null;
const tilesetRef = ref(null);
const opacity = ref(1.0);

// 新增旋转状态
const rotation = reactive({
    heading: 0,
    pitch: 0,
    roll: 0,
});

// 新增模型数据
const modelList = reactive([
    {
        name: "Cesium_Air",
        label: "Cesium 飞机模型",
        url: "http://172.16.21.167:1000/file/models/3/Cesium_Air.glb",
    },
]);

const handler = ref(null);
const drawerVisible = ref(true);
const selectedModel = ref("");
let dashedLine = null;
const glbModels = ref([]);
const keepVal = reactive({
    minHeight: 0,
    maxHeight: 0,
});

// 添加防抖函数
const debounce = (fn, delay = 200) => {
    let timer = null;
    return (...args) => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
};

// 添加相机高度监听相关状态
const cameraHeight = ref(0);
const LABEL_HIDE_HEIGHT = 2000; // 当相机高度超过2000米时隐藏标签

const clickTimer = ref(null);
const clickCount = ref(0);

onMounted(async () => {
    initPage();
});

// 优化后的飞行方法
function flyTo1(center) {
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(...center),
        orientation: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-45),
            roll: 0,
        },
        duration: 3,
    });
}

async function loadB3DMTileset(viewer, center, url) {
    try {
        const tileset = await Cesium.Cesium3DTileset.fromUrl(
            url || "https://xxgtjc.tgmis.cn:1000/file/models/sld/terra_b3dms/tileset.json",
            {
                maximumScreenSpaceError: 1,
                preferLeaves: true,
                preloadWhenHidden: false,
                skipLevelOfDetail: true,
                dynamicScreenSpaceError: true,
                dynamicScreenSpaceErrorDensity: 0.00278,
                dynamicScreenSpaceErrorFactor: 4.0,
                dynamicScreenSpaceErrorHeightFalloff: 0.25,
                immediatelyLoadDesiredLevelOfDetail: false,
                skipLevels: true,
                skipScreenSpaceErrorFactor: 1,
                preloadWhenHidden: true,
                preloadFlightDelay: 1.0,
                maximumMemoryUsage: 2048,
                loadSiblings: false,
                foveatedScreenSpaceError: true,
                foveatedConeSize: 0.1,
                foveatedMinimumScreenSpaceErrorRelaxation: 3.0,
                foveatedInterpolationCallback: (distance, foveatedScreenSpaceError) => {
                    return foveatedScreenSpaceError * Math.pow(distance, 0.5);
                },
                showOutline: false,
                cullWithChildrenBounds: true,
                cullRequestsWhileMoving: true,
                cullRequestsWhileMovingMultiplier: 20.0,
            }
        );

        const boundingSphere = tileset.boundingSphere;
        const cartographic = Cesium.Cartographic.fromCartesian(
            boundingSphere.center
        );
        const minHeight = cartographic.height;
        const maxHeight = cartographic.height + boundingSphere.radius;
        keepVal.minHeight = minHeight;
        keepVal.maxHeight = maxHeight;

        viewer.scene.primitives.add(tileset);
        viewer.zoomTo(tileset);
        if (!center) {
            center = [105.5855290169053, 30.515235578496224, 5200];
        }
        startPolylineTour(center);

        tilesetRef.value = tileset;
    } catch (error) {
        console.error("Failed to load tileset:", error);
    }
}

function initPage() {
    nextTick(async () => {
        viewer = new Cesium.Viewer("cesiumContainer", {
            terrainProvider: await Cesium.createWorldTerrainAsync(), //使用 Cesium 提供的全球地形数据
            geocoder: false,
            homeButton: false,
            sceneModePicker: false,
            timeline: false,
            animation: false,
            baseLayerPicker: false,
            navigationHelpButton: false,
            selectionIndicator: false,
            shadows: false,
            infoBox: false,
            scene3DOnly: true,
            sceneMode: Cesium.SceneMode.SCENE3D,
            useBrowserRecommendedResolution: false,
            resolutionScale: 0.8,
            orderIndependentTranslucency: false,
        });

        viewer.scene.postProcessStages.fxaa.enabled = false;
        viewer.scene.globe.enableLighting = false;
        viewer.scene.fog.enabled = false;
        viewer.scene.sun.show = false;
        viewer.scene.moon.show = false;
        viewer.scene.skyAtmosphere.show = false;
        // 添加相机变化监听
        viewer.camera.changed.addEventListener(onCameraChanged);

        loadB3DMTileset(viewer);
        // createMarker();
        createPoiMarkers();
    });
}

// 添加相机变化处理函数
const onCameraChanged = debounce(() => {
    if (!viewer) return;

    // 获取相机高度
    const cartographic = Cesium.Cartographic.fromCartesian(viewer.camera.position);
    const height = cartographic.height; // 这是相机到椭球面的高度
    cameraHeight.value = height;


    // console.log('相机高度变化:', height, cartographic);

    // 根据高度控制POI标签显示/隐藏
    updatePoiLabelsVisibility(height);
}, 100);

// 更新POI标签显示状态
function updatePoiLabelsVisibility(height) {
    const shouldHideLabels = height > LABEL_HIDE_HEIGHT;

    poiEntities.value.forEach(entity => {
        if (entity.label) {
            entity.label.show = !shouldHideLabels;
        }
    });

    // console.log(`POI标签${shouldHideLabels ? '隐藏' : '显示'} - 相机高度: ${height.toFixed(2)}m`);
}

// 创建POI标记
function createPoiMarkers() {
    clearPoiMarkers();
    visiblePois.value.forEach(poi => {
        createSinglePoiMarker(poi);
    });
}

// 清除POI标记
function clearPoiMarkers() {
    poiEntities.value.forEach(entity => {
        if (viewer && viewer.entities) {
            viewer.entities.remove(entity);
        }
    });
    poiEntities.value = [];
}

// 创建单个POI标记
function createSinglePoiMarker(poi) {
    const position = Cesium.Cartesian3.fromDegrees(
        poi.coordinates.lng,
        poi.coordinates.lat,
        0
    );

    const poiConfig = getPoiConfig(poi.type, poi.isAlert);
    const entity = viewer.entities.add({
        name: poi.name,
        position: position,
        properties: {
            id: poi.id,
            type: 'poi',
            poiData: poi,
        },
        billboard: {
            image: poiConfig.icon,
            show: true,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            alignedAxis: Cesium.Cartesian3.ZERO,
            pixelOffset: new Cesium.Cartesian2(0, -8),
            eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            scale: poi.isAlert ? 0.9 : 0.7,
            width: 20,
            height: 20,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
        label: {
            text: poi.name,
            font: "10pt Microsoft YaHei",
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 1.5,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            pixelOffset: new Cesium.Cartesian2(0, -22),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            show: cameraHeight.value <= LABEL_HIDE_HEIGHT, // 根据当前相机高度决定初始显示状态
            backgroundColor: Cesium.Color.fromCssColorString("rgba(0,0,0,0.7)"),
            showBackground: true,
            backgroundPadding: new Cesium.Cartesian2(6, 3),
        },
    });
    // console.log('entityentity',entity)
    poiEntities.value.push(entity);
}

// 获取深色版本的颜色
function getDarkerColor(color) {
    // 简单的颜色加深函数
    const colorMap = {
        '#52b788': '#2d6a4f',
        '#74c69d': '#52b788',
        '#6a994e': '#40916c',
        '#2d6a4f': '#1b4332',
        '#40916c': '#2d6a4f',
        '#95d5b2': '#74c69d',
        '#a7c957': '#6a994e',
        '#ff4444': '#cc0000'
    };
    return colorMap[color] || '#1b4332';
}

// 获取POI配置
function getPoiConfig(type, isAlert) {
    const configs = {
        6: {
            color: isAlert ? '#ff4444' : '#52b788',
            iconPath: 'M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z',
            viewBox: '0 0 24 24',
            type: 'scenic'
        },
        1: {
            color: isAlert ? '#ff4444' : '#74c69d',
            iconPath: 'M4,6H20V16H4M20,18A2,2 0 0,0 22,16V6C22,4.89 21.1,4 20,4H4C2.89,4 2,4.89 2,6V16A2,2 0 0,0 4,18H10V20H8V22H16V20H14V18H20Z',
            viewBox: '0 0 24 24',
            type: 'monitor'
        },
        3: {
            color: isAlert ? '#ff4444' : '#6a994e',
            iconPath: 'M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M11,14H13V20H11V14M11,4H13V12H11V4Z',
            viewBox: '0 0 24 24',
            type: 'service'
        },
        9: {
            color: isAlert ? '#ff4444' : '#2d6a4f',
            iconPath: 'M11,9H13V22H11V9M9,10A1,1 0 0,0 8,11V15A1,1 0 0,0 9,16H11V10H9M20,10H17V16A1,1 0 0,0 18,17H19A1,1 0 0,0 20,16V10M16,10A1,1 0 0,0 15,11V15A1,1 0 0,0 16,16H18V10H16M7,2V9H8V22H10V2H7Z',
            viewBox: '0 0 24 24',
            type: 'dining'
        },
        8: {
            color: isAlert ? '#ff4444' : '#40916c',
            iconPath: 'M22,16V4A2,2 0 0,0 20,2H8A2,2 0 0,0 6,4V16A2,2 0 0,0 8,18H20A2,2 0 0,0 22,16M16,5H19V8H16V5M16,9H19V12H16V9M16,13H19V16H16V13M8,5H15V8H8V5M8,9H15V12H8V9M8,13H15V16H8V13M2,20V22H4V20H2M6,20V22H20V20H6Z',
            viewBox: '0 0 24 24',
            type: 'entrance'
        },
        10: {
            color: isAlert ? '#ff4444' : '#95d5b2',
            iconPath: 'M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z',
            viewBox: '0 0 24 24',
            type: 'accommodation'
        },
        2: {
            color: isAlert ? '#ff4444' : '#a7c957',
            iconPath: 'M17,18C17.56,18 18,18.44 18,19C18,19.56 17.56,20 17,20C16.44,20 16,19.56 16,19C16,18.44 16.44,18 17,18M1,2V4H3L6.6,11.59L5.24,14.04C5.09,14.32 5,14.65 5,15A2,2 0 0,0 7,17H19V15H7.42A0.25,0.25 0 0,1 7.17,14.75C7.17,14.7 7.18,14.66 7.2,14.63L8.1,13H15.55C16.3,13 16.96,12.58 17.3,11.97L20.88,5H5.21L4.27,2H1M7,18C7.56,18 8,18.44 8,19C8,19.56 7.56,20 7,20C6.44,20 6,19.56 6,19C6,18.44 6.44,18 7,18Z',
            viewBox: '0 0 24 24',
            type: 'shopping'
        }
    };

    const config = configs[type] || configs[6];

    const size = isAlert ? 22 : 18; // 减小SVG图标尺寸

    // 创建唯一标识符
    const uniqueId = Date.now() + Math.random().toString(36).substr(2, 5);

    // 创建简化的SVG图标
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
      <defs>
        <filter id="shadow-${uniqueId}" x="-20%" y="-20%" width="140%" height="140%">
          <feDropShadow dx="1" dy="2" stdDeviation="2" flood-opacity="0.4"/>
        </filter>
        ${isAlert ? `
        <circle id="pulse-${uniqueId}" cx="${size / 2}" cy="${size / 2}" r="${size / 2 - 1}" fill="none" stroke="#ff0000" stroke-width="2" opacity="0.8">
          <animate attributeName="r" values="${size / 2 - 1};${size / 2 + 2};${size / 2 - 1}" dur="2s" repeatCount="indefinite"/>
          <animate attributeName="opacity" values="0.8;0.2;0.8" dur="2s" repeatCount="indefinite"/>
        </circle>
        ` : ''}
      </defs>
      
      <!-- 主背景圆形 -->
      <circle cx="${size / 2}" cy="${size / 2}" r="${size / 2 - 2}" 
              fill="${config.color}" 
              stroke="#ffffff" 
              stroke-width="1.5" 
              filter="url(#shadow-${uniqueId})"/>
      
      ${isAlert ? `<use href="#pulse-${uniqueId}"/>` : ''}
      
      <!-- 图标路径 -->
      <g transform="translate(${(size - 12) / 2}, ${(size - 12) / 2}) scale(0.5)">
        <path d="${config.iconPath}" fill="#ffffff"/>
      </g>
    </svg>
  `;

    // 转换为data URL
    const dataUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);

    return {
        icon: dataUrl,
        color: config.color
    };
}

function createMarker() {
    const position = Cesium.Cartesian3.fromDegrees(
        105.5855290169053,
        30.515235578496224,
        0 // 标记高度
    );
    // 新增特定工程判断
    viewer.entities.add({
        name: "",
        position: position,
        properties: {
            // 新增属性存储工点信息
            id: "id",
            type: "workpoint",
            detail: { id: 1 }, //数据
        },
        billboard: {
            image: img1, // default: undefined
            show: true, // default
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 关键贴地设置
            alignedAxis: Cesium.Cartesian3.ZERO,
            pixelOffset: new Cesium.Cartesian2(0, 0), // default: (0, 0)
            eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0), // default
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
            verticalOrigin: Cesium.VerticalOrigin.CENTER, // default: CENTER
            scale: 1.0, //
            width: 12, // default: undefined
            height: 12, // default: undefined
        },
    });

    //点击事件
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    handlers.push(handler);

    // 单击事件处理
    handler.setInputAction(async (movement) => {
        console.log(123123123);

        clickCount.value++;

        if (clickCount.value === 1) {
            clickTimer.value = setTimeout(() => {
                clickCount.value = 0;
                // 单击事件处理
                const pickedObject = viewer.scene.pick(movement.position);
                if (pickedObject && pickedObject.id && pickedObject.id.properties) {
                    const props = pickedObject.id.properties.getValue();
                    console.log(88888, props);

                    if (props.type === "workpoint") {
                        // console.log("单击了工程点", movement.position);
                    } else if (props.type === "poi") {
                        // POI点击事件
                        const poiData = props.poiData;
                        // console.log("单击了POI", poiData);
                        selectedPoi.value = poiData;
                        emit('poi-selected', poiData);

                        // 如果是监控POI，显示视频弹窗
                        if (poiData.type == '1') {
                            const videoSource = getMonitorVideoSource(poiData.id);
                            // console.log('获取到视频源:', videoSource); // 添加调试日志
                            if (videoSource) {
                                // 确保先清理之前的状态
                                currentMps.value = {};

                                currentVideoSource.value = videoSource;
                                showMonitorVideo.value = true;
                                selectedPoi.value = poiData;
                                document.body.style.overflow = 'hidden';
                                return;
                            }
                        }

                        // 显示POI详情提示
                        showPoiInfo(poiData, movement.position);
                    } else {
                        // 点击空白区域时关闭提示框
                        currentMps.value = {};
                    }
                }
            }, 300); // 300ms延迟来区分单击和双击
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 双击事件处理
    handler.setInputAction((movement) => {
        console.log(12354);
        clearTimeout(clickTimer.value);
        clickCount.value = 0;

        const pickedObject = viewer.scene.pick(movement.position);
        if (pickedObject && pickedObject.id && pickedObject.id.properties) {
            const props = pickedObject.id.properties.getValue();


            if (props.type === "workpoint") {
                console.log("双击了工程点", movement.position);
                // 在这里处理工程点的双击事件
            } else if (props.type === "poi") {
                const poiData = props.poiData;
                console.log("双击了POI", poiData);
                // 修复：异步获取地表高程，确保相机飞到地表上方
                const lng = poiData.coordinates.lng;
                const lat = poiData.coordinates.lat;
                const flyHeight = 6000; // 相对地表高度
                const cartographic = Cesium.Cartographic.fromDegrees(lng, lat);
                Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [cartographic]).then((updatedPositions) => {
                    let surfaceHeight = updatedPositions[0].height;
                    if (typeof surfaceHeight !== 'number' || isNaN(surfaceHeight)) {
                        surfaceHeight = 0;
                    }
                    const finalHeight = surfaceHeight + flyHeight;
                    viewer.camera.flyTo({
                        destination: Cesium.Cartesian3.fromDegrees(
                            lng,
                            lat,
                            finalHeight
                        ),
                        orientation: {
                            heading: Cesium.Math.toRadians(0), // 朝北
                            pitch: Cesium.Math.toRadians(-45), // 俯视
                            roll: 0
                        },
                        duration: 2,
                        easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT
                    });
                });
            }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    // 显示POI信息
    function showPoiInfo(poi, screenPosition) {
        // 更新提示信息
        currentMps.value = {
            id: poi.id,
            name: poi.name,
            type: poi.type,
            data: poi.data,
            isAlert: poi.isAlert
        };

        nextTick(() => {
            const tipElement = document.getElementById("mpsTip");
            if (tipElement) {
                const container = document.getElementById('cesiumContainer');
                if (container) {
                    const rect = container.getBoundingClientRect();
                    const x = screenPosition.x + rect.left;
                    const y = screenPosition.y + rect.top;

                    tipElement.style.left = x + "px";
                    tipElement.style.transform = "translateX(-50%)";
                    tipElement.style.top = (y + 25) + "px";
                    tipElement.style.display = "block";
                }
            }
        });
    }
    const handlerMove = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    // 防抖处理鼠标移动事件
    const moveHandler = debounce(
        (movement) => {
            const pickedObject = viewer.scene.pick(movement.endPosition);
            // 新增容器坐标计算
            const container = document.getElementById('cesiumContainer');
            if (!container) return;
            console.log('movement.endPosition', movement.endPosition)

            console.log('相机状态', {
                position: viewer.camera.position,
                heading: Cesium.Math.toDegrees(viewer.camera.heading),
                pitch: Cesium.Math.toDegrees(viewer.camera.pitch),
                roll: Cesium.Math.toDegrees(viewer.camera.roll)
            });


            const rect = container.getBoundingClientRect();
            const x = movement.endPosition.x + rect.left;
            const y = movement.endPosition.y + rect.top;
            if (
                pickedObject &&
                pickedObject.id &&
                pickedObject.id.properties &&
                !currentMps.value?.id
            ) {
                const props = pickedObject.id.properties.getValue();
                console.log("鼠标移入", props);

                // 检查是否是POI类型
                if (props.type === "poi" && props.poiData) {
                    const poiData = props.poiData;
                    currentMps.value = {
                        id: poiData.id,
                        name: poiData.name,
                        type: poiData.type,
                        data: poiData.data,
                        isAlert: poiData.isAlert
                    };

                    nextTick(() => {
                        let info = document.getElementById("mpsTip");
                        if (info) {
                            info.style.left = x + "px";
                            info.style.transform = "translateX(-50%)";
                            info.style.top = y + 25 + "px";
                            info.style.display = "block";
                        }
                    });
                } else if (props.type === "workpoint") {
                    // 保留原有工程点逻辑
                    currentMps.value = {
                        id: "workpoint_" + props.id,
                        name: "工程标记点",
                        type: "workpoint",
                        data: props.detail
                    };

                    nextTick(() => {
                        let info = document.getElementById("mpsTip");
                        if (info) {
                            info.style.left = x + "px";
                            info.style.transform = "translateX(-50%)";
                            info.style.top = y + 25 + "px";
                            info.style.display = "block";
                        }
                    });
                }
            } else {
                currentMps.value = {};
            }
        }
    );
    // 绑定鼠标事件
    handlerMove.setInputAction(
        moveHandler,
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
    );

    // 销毁旧处理器
    handlers.push(handlerMove);

    // 添加鼠标离开画布时清除提示框的事件
    viewer.canvas.addEventListener('mouseleave', () => {
        currentMps.value = {};
    });
}

// 获取POI类型标签
function getPoiTypeLabel(type) {
    const typeMap = {
        scenic: '景区景点',
        monitor: '监控设备',
        entrance: '出入口',
        accommodation: '住宿服务',
        dining: '餐饮美食',
        service: '公共服务',
        shopping: '购物商业',
        workpoint: '工程标记'
    };
    return typeMap[type] || type;
}

// 监听筛选变化
watch(() => props.activeFilter, (newFilter) => {
    if (viewer) {
        createPoiMarkers(); // 重新创建POI标记
    }
}, { immediate: false });

function startPolylineTour(center) {
    // 获取线路坐标点
    // 获取多边形的顶点位置
    // 创建漫游动画
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(...center),
        orientation: {
            heading: Cesium.Math.toRadians(0), // 正北方向
            pitch: Cesium.Math.toRadians(-90), // 俯视角度
            roll: 0,
        },
        duration: 3, // 飞行时间(秒)
        // radius:10000,
    });
}
function changeMap(data) {
    if (!viewer) return;

    console.log('data', data);
    nextTick(() => {
        if (tilesetRef.value && viewer.scene) {
            viewer.scene.primitives.remove(tilesetRef.value);
            tilesetRef.value = null;
        }

        handlers.forEach((handler) => {
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        });
        handlers.length = 0;
        // if (infoBox && document.body.contains(infoBox)) {
        //     document.body.removeChild(infoBox);
        //     infoBox = null;
        // }
        loadB3DMTileset(viewer, data.position, data.url);
        if (data.id == 1) {
            createPoiMarkers();
        } else {
            clearPoiMarkers();
        }
    })
}
// 在onMounted之后添加卸载逻辑
onBeforeUnmount(() => {
    // 移除相机变化监听
    if (viewer && viewer.camera) {
        viewer.camera.changed.removeEventListener(onCameraChanged);
    }

    if (tilesetRef.value && viewer.scene) {
        viewer.scene.primitives.removeAll();
        tilesetRef.value = null;
    }

    handlers.forEach((handler) => {
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    });
    handlers.length = 0;

    if (infoBox && document.body.contains(infoBox)) {
        document.body.removeChild(infoBox);
        infoBox = null;
    }

    glbModels.value.forEach((entity) => {
        const primitives = viewer?.scene?.primitives;
        if (entity.primitive) {
            primitives.remove(entity.primitive);
        }
    });

    clearPoiMarkers();

    if (videoPlayerRef.value) {
        videoPlayerRef.value.pause();
        videoPlayerRef.value.src = '';
    }
    showMonitorVideo.value = false;
    currentVideoSource.value = '';
    document.body.style.overflow = '';

    if (viewer) {
        viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
        viewer = null;
    }
    glbModels.value = null;
    currentMps.value = null;
});

// 关闭监控视频弹窗
const closeMonitorVideo = () => {
    showMonitorVideo.value = false;
    currentVideoSource.value = '';
    selectedPoi.value = null; // 重置选中的POI状态

    if (videoPlayerRef.value) {
        videoPlayerRef.value.pause();
        videoPlayerRef.value.src = ''; // 清除视频源
    }

    document.body.style.overflow = '';
};

defineExpose({
    changeMap
});
</script>

<style scoped>
#cesiumContainer {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background: rgba(14, 50, 51, 0.95);
}

/* 隐藏Cesium水印 */
:deep(.cesium-widget-credits) {
    display: none !important;
}

.mps-tip {
    min-width: 280px;
    max-width: 350px;
    background: rgba(0, 0, 0, 0.95);
    color: #fff;
    border: 1px solid rgba(0, 255, 136, 0.3);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(15px);
    position: absolute;
    z-index: 1000;
    display: none;
    padding: 0;
}

.tip-header {
    padding: 15px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 255, 136, 0.1);
    border-radius: 12px 12px 0 0;
    position: relative;
}

.tip-header h4 {
    margin: 0 0 8px 0;
    color: #00ff88;
    font-size: 1.1rem;
}

.tip-type {
    background: rgba(0, 255, 136, 0.2);
    color: #00ff88;
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 0.8rem;
    margin-right: 8px;
}

.tip-type.scenic {
    background: rgba(82, 183, 136, 0.3);
}

.tip-type.monitor {
    background: rgba(116, 198, 157, 0.3);
}

.tip-type.service {
    background: rgba(106, 153, 78, 0.3);
}

.tip-type.dining {
    background: rgba(45, 106, 79, 0.3);
}

.tip-type.workpoint {
    background: rgba(255, 193, 7, 0.3);
    color: #ffc107;
}

.alert-badge {
    background: rgba(255, 68, 68, 0.2);
    color: #ff4444;
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 0.75rem;
    border: 1px solid #ff4444;
}

.tip-content {
    padding: 20px;
}

.tip-content p {
    margin: 8px 0;
    font-size: 0.9rem;
    line-height: 1.4;
}

.label {
    color: rgba(255, 255, 255, 0.7);
    margin-right: 8px;
}

.description {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.85rem;
    line-height: 1.4;
}

.close-btn {
    position: absolute;
    top: 15px;
    right: 20px;
    background: none;
    border: none;
    color: #ffffff;
    font-size: 1.5rem;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.3s ease;
}

.close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
}

/* 监控视频弹窗样式 */
.monitor-video-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
    margin: 0;
    transform: none;
}

.video-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(5px);
    z-index: 1;
}

.video-modal-content {
    position: relative;
    background: rgba(0, 0, 0, 0.95);
    border: 2px solid rgba(0, 255, 136, 0.5);
    border-radius: 16px;
    padding: 0;
    width: 700px;
    max-width: calc(100vw - 40px);
    max-height: calc(100vh - 40px);
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
    margin: 0;
    z-index: 10;
    flex-shrink: 0;
}

.video-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: rgba(0, 255, 136, 0.1);
    border-bottom: 1px solid rgba(0, 255, 136, 0.3);
}

.video-header h3 {
    margin: 0;
    color: #00ff88;
    font-size: 1.2rem;
}

.video-close-btn {
    background: none;
    border: none;
    color: #ffffff;
    font-size: 2rem;
    cursor: pointer;
    padding: 0;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.video-close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
    color: #ff6b6b;
}

.video-container {
    width: 100%;
    background: #000;
    display: flex;
    justify-content: center;
    align-items: center;
}

.monitor-video {
    width: 100%;
    height: 360px;
    max-width: 100%;
    max-height: 50vh;
    background: #000;
    object-fit: contain;
}

.video-info {
    padding: 15px 20px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.video-info .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
}

.video-info .label {
    color: rgba(255, 255, 255, 0.7);
    font-size: 0.9rem;
}

.video-info .value {
    color: white;
    font-weight: 500;
    font-size: 0.9rem;
}

/* 响应式设计 */
@media screen and (max-width: 1400px) {
    .video-modal-content {
        width: 600px;
    }

    .monitor-video {
        height: 270px;
    }
}

@media screen and (max-width: 768px) {
    .monitor-video-modal {
        padding: 10px;
    }

    .video-modal-content {
        width: 100%;
        max-width: calc(100vw - 20px);
        max-height: calc(100vh - 20px);
    }

    .monitor-video {
        height: auto;
        max-height: 40vh;
    }

    .video-header h3 {
        font-size: 1rem;
    }

    .video-info {
        padding: 12px 15px;
    }
}
</style>
